package org.hzandyy.zookeeper.demo;

import org.apache.commons.lang3.ThreadUtils;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.time.Duration;
import java.util.Random;

/**
 * Zookeeper 连接信息
 */
public class BaseConnection {

    protected static final String host = "127.0.0.1:2181";
    protected static final Random rand = new Random();
    protected static byte[] emptyContent = new byte[0];

    protected ZooKeeper zooKeeper;

    protected String serverId = Integer.toHexString(rand.nextInt());
    protected Watcher watcher;
    protected boolean connected;
    protected boolean expired;

    public BaseConnection() {
        this(System.out::println);
    }

    public BaseConnection(Watcher watcher) {
        this.watcher = watcher;
        System.out.println("server id: " + serverId);
    }

    public void startZK() throws IOException {
        zooKeeper = new ZooKeeper(host, 15000, this.watcher);
    }

    public void stopZK() throws InterruptedException {
        zooKeeper.close();
    }

    public static KeeperException.Code getKeeperCode(int rc) {
        return KeeperException.Code.get(rc);
    }

    public static void main(String[] args) throws Exception {
        BaseConnection connection = new BaseConnection();
        ThreadUtils.sleep(Duration.ofMinutes(1));
        connection.stopZK();
    }

}
